package com.yusong.algorithm.stack;

import java.util.LinkedList;
import java.util.List;

public class EvalRPN150 {

    public static void main(String[] args) {

        EvalRPN150 main = new EvalRPN150();

        String[] tokens = {"2","1","+","3","*"};
        int res = main.evalRPN(tokens);

        System.out.println(res);

    }


    /**
     两个栈（list）；
     遇到操作符，就从数据栈中取出两个数据计算，压入结果。知道没有操作符
     这个操作符没有优先级的吗？？？
     **/
    public int evalRPN(String[] tokens) {
        if(tokens != null || tokens.length <= 0){
            return 0;
        }

        LinkedList<Integer> dataStack = new LinkedList<>();
        int length = tokens.length;
        for(int i = 0; i< length; i++){
            String str = tokens[i];
            if("+".equals(str)){
                Integer data1 = dataStack.removeLast();
                Integer data0 = dataStack.removeLast();
                Integer data = data0 + data1;
                dataStack.add(data);
                continue;
            }else if("-".equals(str)){
                Integer data1 = dataStack.removeLast();
                Integer data0 = dataStack.removeLast();
                Integer data = data0 - data1;
                dataStack.add(data);
                continue;
            }else if("*".equals(str)){
                Integer data1 = dataStack.removeLast();
                Integer data0 = dataStack.removeLast();
                Integer data = data0 * data1;
                dataStack.add(data);
                continue;
            }else if("/".equals(str)){
                Integer data1 = dataStack.removeLast();
                Integer data0 = dataStack.removeLast();
                Integer data = data0 / data1;
                dataStack.add(data);
                continue;
            }else{
                Integer data = Integer.parseInt(str);
                dataStack.add(data);
            }

        }

        return dataStack.get(0);
    }
}
